package com.design.reactor.stretchIO._1_singleReactorSingleThread.impl.handler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class ReaderAndWriterHandler implements Handler {
    static final int MAX_IN = 1024;
    static final int MAX_OUT = 1024;
    ByteBuffer input = ByteBuffer.allocate(MAX_IN);
    ByteBuffer output = ByteBuffer.allocate(MAX_OUT);
    static final int READING = 0, SENDING = 1;
    int state = READING;

    public ReaderAndWriterHandler(Selector selector, SocketChannel channel) throws IOException {
        System.out.println("----ReaderAndWriterHandler的构造函数" );
        channel.configureBlocking(false);
        SelectionKey selectionKey = channel.register(selector, 0);//注册一个不存在的事件
        selectionKey.attach(this);
        selectionKey.interestOps(SelectionKey.OP_READ);//注册读事件
        selector.wakeup();//唤醒前一个阻塞的socket
    }


    public void handle(Selector selector, SelectableChannel channel, SelectionKey selectionKey) {
        SocketChannel socketChannel = (SocketChannel)channel;
        try {
            if (state == READING) {
                read( selector,  socketChannel,  selectionKey);
            } else if (state == SENDING) {
                write( selector,  socketChannel,  selectionKey);
            }
        } catch (IOException ignored) {
            // ignored.
        }
    }

    void read(Selector selector, SocketChannel channel, SelectionKey selectionKey) throws IOException {
        channel.read(input);
        input.flip();
        Charset ch = Charset.forName("UTF-8");
        String msg = String.valueOf(ch.decode(input).array());
        process();
        state = SENDING;
        selectionKey.interestOps(SelectionKey.OP_WRITE);
    }

    void write(Selector selector, SocketChannel channel, SelectionKey selectionKey) throws IOException {
        String msg = "to client write content";
        output.put(msg.getBytes());
        output.flip();
        channel.write(output);
        if (outputIsComplete()) {
            selectionKey.cancel();
        }
    }

    boolean inputIsComplete() {
        // 加入实现
        return true;
    }

    boolean outputIsComplete() {
        // 加入实现
        return true;
    }

    void process() {
        // 加入实现
    }
}
